
package com.kugou.game.sdk.ui.activity;

import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.IEventDataField;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnRegisterListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.ui.widget.RecomendUsernamePopWindow;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Process;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * 描述:通过用户名注册页面
 * 
 * @author liux
 * @since 2013-12-14 下午07:18:07
 */
public class RegisterActivity extends BaseCommonTitleFragmentActivity {
    /**
     * 消息相关
     */
    private static final int MSG_REQUEST_REGISTER = 1;// 提交注册请求

    private static final int MSG_REGISTER_SUCCESS = 2;// 注册成功

    private static final int MSG_REGISTER_FAILE = 3;// 注册失败

    private static final int MSG_SHOW_RECOMMEND_NAME = 4;// 注册名已存在，返回推荐注册名

    /**
     * 控件相关
     */

    private TextView mRegisterAccountTips;

    private TextView payRegisterTips;

    private TextView payAgreeKugouLicenseText;

    private CheckBox payAgreeKugouLicense;

    private EditText mUserName;

    private EditText mPassword;

    private ImageView mUserNameClear;

    private ImageView mPasswordClear;

    private Button mRegister;

    private Button mCannel;

    private LoadingView mLoadingView;

    private RelativeLayout mMainView;

    private RelativeLayout mRegisterSuccessLayout;

    private Button mEnterGameBtn;

    User mNewUser;

    private View mHiddenView;

    private int mFrom;

    private ArrayList<String> mRecommendUsernames;

    private RecomendUsernamePopWindow mPopWindow = null;

    private ScrollView mLayoutScrollView;

    private TextView mRegisterByPhoneTextView;

    /**
     * 当前用户是否是正式用户（跳转来注册页面之前）。用于判断切换账号是否弹出重启对话框和重启。
     */
    private boolean mRegistered;

    /**
     * 固定充值金额（来自于固定充值界面，用于判断注册成功后回跳转至固定充值界面）
     */
    private int fixedNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId = Rx.layout.kg_register_activity;
        if (layoutId != 0) {
            setContentView(layoutId);
            // 设置标题
            setCommonTitle(Rx.string.kg_register_title);
            initViews();
            mFrom = getIntent().getIntExtra(FROM_ACTION_KEY, FROM_NORMAL);
            fixedNum = getIntent().getIntExtra(RechargeActivity.FIXED_MONEY_NUM, -1);
        } else {
            showToast(Rx.string.kg_layout_not_found);
        }
    }

    /**
     * 初始化页面
     */
    private void initViews() {
        mLayoutScrollView = (ScrollView) findViewById(Rx.id.kg_layout_scrollview);
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            int padding = (int) (90 * getResources().getDisplayMetrics().density);
            mLayoutScrollView.setPadding(padding, 0, padding, 0);
        }

        mMainView = (RelativeLayout) findViewById(Rx.id.kg_layout_user_register);
        mHiddenView = findViewById(Rx.id.kg_hidden_view);
        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loading);
        mLoadingView.setText("正在注册，请稍候...");
        // 用户协议
        int payAgreeKugouLicenseID = Rx.id.kg_agree_kugou_license;
        payAgreeKugouLicense = (CheckBox) findViewById(payAgreeKugouLicenseID);

        int payAgreeKugouLicenseTextId = Rx.id.kg_agree_kugou_license_text;
        payAgreeKugouLicenseText = (TextView) findViewById(payAgreeKugouLicenseTextId);
        payAgreeKugouLicenseText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showLicenseDialog();
            }
        });
        mRegisterAccountTips = (TextView) findViewById(Rx.id.kg_register_account_tips);
        // 注册提示文本
        int payRegisterTipsID = Rx.id.kg_register_tips;
        payRegisterTips = (TextView) findViewById(payRegisterTipsID);
        // 用户名
        mUserName = (EditText) findViewById(Rx.id.kg_login_username);
        mUserNameClear = (ImageView) findViewById(Rx.id.kg_login_username_clear);

        mUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mUserNameClear.setVisibility(View.INVISIBLE);
                } else {
                    mUserNameClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mUserName.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = mUserName.getText().toString().trim();
                if (hasFocus) {
                    mRegisterAccountTips.setVisibility(View.GONE);
                } else if (!TextUtils.isEmpty(str)) {
                    checkUserName();
                }
            }
        });
        mUserNameClear.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mUserName.setText("");
                // mUserNameCorrect = false;
            }
        });
        // 密码
        mPassword = (EditText) findViewById(Rx.id.kg_login_password);
        mPasswordClear = (ImageView) findViewById(Rx.id.kg_login_password_clear);
        mPassword.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mPasswordClear.setVisibility(View.INVISIBLE);
                } else {
                    mPasswordClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPassword.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = mPassword.getText().toString().trim();
                if (hasFocus) {
                    hideRegisterTips();
                } else {
                    if (!TextUtils.isEmpty(str)) {
                        if (checkUserName()) {
                            checkPassword();
                        } else {
                            hideRegisterTips();
                        }
                    }
                }
            }
        });
        mPasswordClear.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPassword.setText("");
            }
        });
        // 提交注册
        mRegister = (Button) findViewById(Rx.id.kg_summit_register_button);
        mRegister.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });
        // 取消注册
        mCannel = (Button) findViewById(Rx.id.kg_cancel_register_button);
        mCannel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                exitRegisterPage();
            }
        });

        mRegisterByPhoneTextView = (TextView) findViewById(Rx.id.kg_tv_register_by_phone);
        mRegisterByPhoneTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到用户名注册页面
                Intent intent = new Intent(RegisterActivity.this, RegisterByPhoneActivity.class);
                intent.putExtra(FROM_ACTION_KEY, mFrom);
                intent.putExtra(RechargeActivity.FIXED_MONEY_NUM, fixedNum);
                startActivity(intent);
                finish();
            }
        });

        mRegisterSuccessLayout = (RelativeLayout) findViewById(Rx.id.kg_rl_register_success);
        mEnterGameBtn = (Button) findViewById(Rx.id.kg_btn_enter_game);
        mEnterGameBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                registerSuccess();
            }
        });

        // 如果从巨炮游戏中心跳入，隐藏一些入口
        if (mFrom == FROM_GAME_CENTER) {
            mEnterGameBtn.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 提交注册前检查所有输入信息格式是否正确
     */
    private boolean checkAllInputInfo() {
        if (checkUserName()) {
            return checkPassword();
        }
        return false;

    }

    /**
     * 检查用户名
     */
    private boolean checkUserName() {
        String text = mUserName.getText().toString().trim();
        if (isUserNameCorrect(text)) {
            mRegisterAccountTips.setVisibility(View.GONE);
            return true;
        } else {
            mRegisterAccountTips.setVisibility(View.VISIBLE);
            return false;
        }
    }

    /**
     * 检查密码
     */
    private boolean checkPassword() {
        String text = mPassword.getText().toString();
        if (isPasswordCorrect(text)) {
            hideRegisterTips();
            return true;
        } else {
            showRegisterTips(getString(Rx.string.kg_password_input_long_tips));
            return false;
        }
    }

    /**
     * 验证用户名格式
     * 
     * @param userName
     * @return
     */
    private boolean isUserNameCorrect(String userName) {
        if (!TextUtils.isEmpty(userName)) {
            // Pattern pattern = Pattern.compile("^[0-9a-zA-Z]{4,20}$");
            // Pattern pattern =
            // Pattern.compile("^[a-zA-Z]{1}[0-9a-zA-Z]{3,19}$");
            // Matcher matcher = pattern.matcher(userName);
            // Pattern patternnumber =
            // Pattern.compile("^[0-9]{1}[0-9a-zA-Z]{3,19}$");
            // Matcher matchernumber = patternnumber.matcher(userName);
            // if (matchernumber.find()) {
            // showToast("帐号首字母不能是数字");
            // return false;
            // }
            // return matcher.find();

            // 使用手机酷狗的注册判断规则
            if (AppUtil.isSpatialChart(userName)) {
                showToast("账号不能使用：空格、符号等特殊字符");
                return false;
            } else if (AppUtil.length(userName) > 20 || AppUtil.length(userName) < 4
                    || AppUtil.isNumeric(userName.substring(0, 1))) {
                showToast("请输入4-20位长度的账号,首位非数字");
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证密码格式
     * 
     * @param password
     * @return
     */
    private boolean isPasswordCorrect(String password) {
        if (!TextUtils.isEmpty(password)) {
            // Pattern pattern = Pattern.compile("^[0-9a-zA-Z]{6,16}$");
            // Matcher matcher = pattern.matcher(password);
            // return matcher.find();

            // 使用手机酷狗的密码判断规则
            if (password.length() > 16 || password.length() < 6) {
                showToast("请设置6-16位字母/数字的密码");
                return false;
            } else if (AppUtil.isSpatialChart(password) || AppUtil.isHaveChinese(password)) {
                showToast("密码不能包含：空格、符号等特殊字符");
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 弹出注册输入错误信息黄色提示栏
     */
    private void showRegisterTips(String tips) {
        // 如果有特殊格式，请使用HTML格式。
        payRegisterTips.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏注册输入错误信息黄色提示栏
     */
    private void hideRegisterTips() {
        payRegisterTips.setVisibility(View.GONE);
    }

    /**
     * 点击注册按钮
     */
    private void register() {
        if (!payAgreeKugouLicense.isChecked()) {
            showToast("请勾选《酷狗游戏通行证用户协议》");
            return;
        }
        hideSoftInput(this);
        if (checkAllInputInfo()) {
            if (!NetWorkUtil.isNetworkAvailable(this)) {
                showToast("请检查您的网络连接");
                return;
            }

            User userData = UserManager.getInstance().getCurrentUserInternal();
            if (userData != null) {
                mRegistered = userData.isRegistered();
                if (mRegistered && mFrom == FROM_CHANGE_ACCOUNT// 切换账号
                        && SDKControler.isNeedRestartWhenAccountChanged()) {
                    // 弹出重启确认对话框
                    showRebootConfirmDialog();
                } else {
                    submitRegister();
                }
            } else {
                submitRegister();
            }
        }
    }

    /**
     * 提交注册
     */
    private void submitRegister() {
        mLayoutScrollView.setVisibility(View.GONE);
        mMainView.setVisibility(View.GONE);
        mLoadingView.setVisibility(View.VISIBLE);
        sendEmptyBackgroundMessage(MSG_REQUEST_REGISTER);
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_REQUEST_REGISTER:
                // 获取注册请求相关参数
                String userName = mUserName.getText().toString();
                String password = mPassword.getText().toString();
                String tempName;
                User userData = UserManager.getInstance().getLastestUserDataOnSPAndSDcard();
                if (userData != null && !userData.isRegistered()) {
                    tempName = userData.getOpenId();
                } else {
                    tempName = "";
                }
                // 发送注册请求
                final Message message = new Message();
                UserManager.getInstance().registerByAccount(userName, tempName, password,
                        new OnRegisterListener() {
                            @Override
                            public void onSuccess(User newUser) {
                                if (SDKControler.getGameType() == BaseSDKConfig.GAME_TYPE_ONLINE) {
                                    AppUtil.writeDataToSSO(newUser);
                                }
                                message.what = MSG_REGISTER_SUCCESS;
                                message.obj = newUser;
                            }

                            @Override
                            public void onFailed(String errorMsg, String errorCode) {
                                message.what = MSG_REGISTER_FAILE;
                                message.obj = errorMsg;

                            }

                            @Override
                            public void onRecommendRegisterName(ArrayList<String> names) {
                                message.what = MSG_SHOW_RECOMMEND_NAME;
                                message.obj = names;
                            }

                        });
                sendUiMessage(message);
                break;
        }
    }

    private void registerSuccess() {
        Bundle bundle = new Bundle();
        if (mFrom == FROM_RECHARGE) {// 如果来自充值页面，则返回充值
            Intent intent = new Intent(this, RechargeActivity.class);
            intent.putExtra(USER_NICKNAME_KEY, mNewUser.getAccountName());
            intent.putExtra(RechargeActivity.FIXED_MONEY_NUM, fixedNum);
            startActivity(intent);
            finish();
        } else if (mRegistered && mFrom == FROM_CHANGE_ACCOUNT) {// 如果来自切换账号,根据配置决定是否重启
            bundle.putSerializable(IEventDataField.EXTRA_USER, mNewUser);
            PlatformEventDispatcher.sendEvent(IEventCode.ACCOUNT_CHANGED_SUCCESS, bundle);
            AppUtil.handleActionsAfterLoginSuccess(IEventCode.ACCOUNT_CHANGED_SUCCESS);
            LogUtil.d("callback", "RegisterActivity:ACCOUNT_CHANGED_SUCCESS");
            // 判断是否需要重启
            boolean isReboot = SDKControler.isNeedRestartWhenAccountChanged();
            if (isReboot) {// 重启游戏
                PlatformEventDispatcher.sendEvent(IEventCode.INTENT_TO_REBOOT_APP, bundle);
                LogUtil.d("callback", "RegisterActivity:INTENT_TO_REBOOT_APP");
                reStart();
            } else {// 返回游戏
                sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            }
        } else if (mFrom == FROM_BEFORE_ENTER_GAME_LOGIN
                || mFrom == FROM_BEFORE_ENTER_GAME_REGISTER) {// 登录或进入游戏之前进入注册，注册成功后通知进入游戏
            bundle.putSerializable(IEventDataField.EXTRA_USER, mNewUser);
            PlatformEventDispatcher.sendEvent(IEventCode.ENTER_GAME_SUCCESS, bundle);
            AppUtil.handleActionsAfterLoginSuccess(IEventCode.ENTER_GAME_SUCCESS);
            LogUtil.d("callback", "RegisterActivity:ENTER_GAME_SUCCESS");
            // 关闭SDK页面
            sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            finish();
        } else if (mFrom == FROM_GIFTBAG_REGISTER) {// 从礼包页面进入
            bundle.putSerializable(IEventDataField.EXTRA_USER, mNewUser);
            PlatformEventDispatcher.sendEvent(IEventCode.REGISTER_SUCCESS, bundle);
            AppUtil.handleActionsAfterLoginSuccess(IEventCode.REGISTER_SUCCESS);
            LogUtil.d("callback", "RegisterActivity:REGISTER_SUCCESS");
            sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            // 回到礼包页面
            Intent intent = new Intent(this, GiftBagActivity.class);
            startActivity(intent);

        } else if (mFrom == FROM_GAME_CENTER) {// 来自巨炮游戏中心
            sendBroadcast(new Intent(SDKActions.ACTION_REGISTER_SUCCESS));
            finish();
        } else {// 进入游戏之后的正常注册，包括激活账号
            bundle.putSerializable(IEventDataField.EXTRA_USER, mNewUser);
            PlatformEventDispatcher.sendEvent(IEventCode.REGISTER_SUCCESS, bundle);
            LogUtil.d("callback", "RegisterActivity:REGISTER_SUCCESS");
            sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            finish();
        }
    }

    private boolean registerSuccess = false;

    @Override
    public void handleUiMessage(Message msg) {
        if (isFinishing()) {
            return;
        }
        switch (msg.what) {
            case MSG_REGISTER_SUCCESS:// 注册成功
                mLayoutScrollView.setVisibility(View.GONE);
                mRegisterSuccessLayout.setVisibility(View.VISIBLE);
                registerSuccess = true;
                showToast("注册成功");
                mNewUser = (User) msg.obj;

                break;
            case MSG_REGISTER_FAILE:// 注册失败
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mMainView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);

                String prompt = (String) msg.obj;
                showToast(prompt);
                break;
            case MSG_SHOW_RECOMMEND_NAME:// 陈列推荐用户名，在用户输入的用户已经被注册的情况下
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mMainView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);

                mRecommendUsernames = (ArrayList<String>) msg.obj;
                mPopWindow = new RecomendUsernamePopWindow(this, mRecommendUsernames,
                        mRecommendNamesClickListener);
                int[] position = new int[2];
                mUserName.getLocationOnScreen(position);
                if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {// 横屏
                    mPopWindow.showAsDropDown(mHiddenView, 0, 0);
                } else {// 竖屏
                    mPopWindow.showAsDropDown(mHiddenView, 0, 0);
                }
                break;
        }
    }

    /**
     * 注册推荐账号列表点击监听
     */
    private final OnClickListener mRecommendNamesClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Object obj = v.getTag();
            if (obj != null) {
                int pos = (Integer) obj;
                mUserName.setText(mRecommendUsernames.get(pos));
                mUserName.setSelection(mUserName.length());
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
            }
        }
    };

    private void showLicenseDialog() {
        final BaseConfirmDialog confirmDialog = new BaseConfirmDialog(this);
        confirmDialog.setMessage(getString(Rx.string.kg_license_long));
        confirmDialog.setCancelBtnVisibility(false);
        confirmDialog.setOKBtnText("我知道了");
        confirmDialog.setDialogHeight((int) (250 * getResources().getDisplayMetrics().density));
        confirmDialog.setOKClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmDialog.dismiss();
            }
        });
        confirmDialog.show();
    }

    private void showRebootConfirmDialog() {
        final BaseConfirmDialog confirmDialog = new BaseConfirmDialog(this);
        confirmDialog.setMessage(getString(Rx.string.kg_register_account_confirm));
        confirmDialog.setOKClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmDialog.dismiss();
                submitRegister();
            }
        });
        confirmDialog.show();
    }

    /**
     * 关闭并重启应用
     */
    private void reStart() {
        AppUtil.gc();
        finish();
        clearAllActivityAndRestart();
        // 关闭当前游戏进程，退出应用
        Process.killProcess(Process.myPid());
    }

    /**
     * 清除所有页面并重启应用
     */
    private void clearAllActivityAndRestart() {
        Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(
                getBaseContext().getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    @Override
    protected void onBackBtnClick() {
        exitRegisterPage();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitRegisterPage();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出注册界面
     */
    private void exitRegisterPage() {
        if (registerSuccess) {
            registerSuccess();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
